from django.db import models
from django.contrib.auth.models import User
from books.models import Book


class Follow(models.Model):
    """关注关系"""
    
    id = models.BigAutoField(
        primary_key=True,
        verbose_name='编号',
        db_comment='关注ID'
    )
    follower = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='following',
        verbose_name='关注者',
        db_comment='关注者ID'
    )
    following = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='followers',
        verbose_name='被关注者',
        db_comment='被关注者ID'
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='关注时间',
        db_comment='关注时间'
    )
    
    class Meta:
        db_table = 'campus_follow'
        db_table_comment = '用户关注关系表'
        verbose_name = '关注'
        verbose_name_plural = '关注'
        unique_together = ('follower', 'following')
        ordering = ['-created_at']
    
    def __str__(self):
        return f'{self.follower.username} 关注 {self.following.username}'


class Comment(models.Model):
    """评论"""
    
    id = models.BigAutoField(
        primary_key=True,
        verbose_name='编号',
        db_comment='评论id'
    )
    book = models.ForeignKey(
        Book,
        on_delete=models.CASCADE,
        related_name='comments',
        verbose_name='关联书籍',
        db_comment='关联书籍'
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        verbose_name='评论用户',
        db_comment='评论用户'
    )
    content = models.TextField(
        verbose_name='评论内容',
        db_comment='评论内容'
    )
    parent = models.ForeignKey(
        'self',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='replies',
        verbose_name='父评论',
        db_comment='父评论id(回复)'
    )
    like_count = models.IntegerField(
        default=0,
        verbose_name='点赞数',
        db_comment='点赞数'
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        db_index=True,
        verbose_name='评论时间',
        db_comment='评论时间'
    )
    
    class Meta:
        db_table = 'campus_comment'
        db_table_comment = '书籍评论表'
        verbose_name = '评论'
        verbose_name_plural = '评论'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['book', 'created_at']),
            models.Index(fields=['user', 'created_at']),
        ]
    
    def __str__(self):
        return f'{self.user.username} 评论 {self.book.title}'


class Favorite(models.Model):
    """收藏"""
    
    id = models.BigAutoField(
        primary_key=True,
        verbose_name='编号',
        db_comment='收藏ID'
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='favorites',
        verbose_name='用户',
        db_comment='用户ID'
    )
    book = models.ForeignKey(
        Book,
        on_delete=models.CASCADE,
        related_name='favorited_by',
        verbose_name='书籍',
        db_comment='书籍ID'
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='收藏时间',
        db_comment='收藏时间'
    )
    
    class Meta:
        db_table = 'campus_favorite'
        db_table_comment = '用户收藏表'
        verbose_name = '收藏'
        verbose_name_plural = '收藏'
        unique_together = ('user', 'book')
        ordering = ['-created_at']
    
    def __str__(self):
        return f'{self.user.username} 收藏 {self.book.title}'


class ReadingGroup(models.Model):
    """读书小组"""
    
    id = models.BigAutoField(
        primary_key=True,
        verbose_name='编号',
        db_comment='小组ID'
    )
    name = models.CharField(
        max_length=100,
        verbose_name='小组名称',
        db_comment='小组名称'
    )
    description = models.TextField(
        verbose_name='小组描述',
        db_comment='小组描述'
    )
    creator = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='created_groups',
        verbose_name='创建者',
        db_comment='创建者ID'
    )
    members = models.ManyToManyField(
        User,
        through='GroupMembership',
        related_name='joined_groups',
        verbose_name='成员',
        db_comment='小组成员'
    )
    cover_image = models.ImageField(
        upload_to='group_covers/',
        null=True,
        blank=True,
        verbose_name='封面图片',
        db_comment='小组封面'
    )
    max_members = models.IntegerField(
        default=50,
        verbose_name='最大成员数',
        db_comment='最大成员数'
    )
    is_public = models.BooleanField(
        default=True,
        verbose_name='是否公开',
        db_comment='是否公开'
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间',
        db_comment='创建时间'
    )
    
    class Meta:
        db_table = 'campus_reading_group'
        db_table_comment = '读书小组表'
        verbose_name = '读书小组'
        verbose_name_plural = '读书小组'
        ordering = ['-created_at']
    
    def __str__(self):
        return self.name


class GroupMembership(models.Model):
    """小组成员关系"""
    
    ROLE_CHOICES = [
        ('owner', '组长'),
        ('admin', '管理员'),
        ('member', '成员'),
    ]
    
    id = models.BigAutoField(
        primary_key=True,
        verbose_name='编号',
        db_comment='成员关系ID'
    )
    group = models.ForeignKey(
        ReadingGroup,
        on_delete=models.CASCADE,
        verbose_name='小组',
        db_comment='小组ID'
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        verbose_name='用户',
        db_comment='用户ID'
    )
    role = models.CharField(
        max_length=20,
        choices=ROLE_CHOICES,
        default='member',
        verbose_name='角色',
        db_comment='角色'
    )
    joined_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='加入时间',
        db_comment='加入时间'
    )
    
    class Meta:
        db_table = 'campus_group_membership'
        db_table_comment = '小组成员关系表'
        verbose_name = '小组成员'
        verbose_name_plural = '小组成员'
        unique_together = ('group', 'user')
        ordering = ['-joined_at']
    
    def __str__(self):
        return f'{self.user.username} - {self.group.name}'


class Post(models.Model):
    """动态"""
    
    id = models.BigAutoField(
        primary_key=True,
        verbose_name='编号',
        db_comment='动态ID'
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='posts',
        verbose_name='发布者',
        db_comment='发布者ID'
    )
    book = models.ForeignKey(
        Book,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='posts',
        verbose_name='关联书籍',
        db_comment='关联书籍'
    )
    group = models.ForeignKey(
        ReadingGroup,
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='posts',
        verbose_name='关联小组',
        db_comment='关联小组'
    )
    content = models.TextField(
        verbose_name='动态内容',
        db_comment='动态内容'
    )
    images = models.JSONField(
        default=list,
        blank=True,
        verbose_name='图片列表',
        db_comment='图片列表'
    )
    like_count = models.IntegerField(
        default=0,
        verbose_name='点赞数',
        db_comment='点赞数'
    )
    comment_count = models.IntegerField(
        default=0,
        verbose_name='评论数',
        db_comment='评论数'
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        db_index=True,
        verbose_name='发布时间',
        db_comment='发布时间'
    )
    
    class Meta:
        db_table = 'campus_post'
        db_table_comment = '用户动态表'
        verbose_name = '动态'
        verbose_name_plural = '动态'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['user', 'created_at']),
            models.Index(fields=['group', 'created_at']),
        ]
    
    def __str__(self):
        return f'{self.user.username} 的动态 - {self.created_at.strftime("%Y-%m-%d")}'
